package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author 彭于晏
 * @date 2025-05-26
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //校验老人信息是否存在
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        elderQueryWrapper.eq(Elder::getId, checkInApplyDto.getCheckInElderDto().getIdCardNo());
        elderQueryWrapper.eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elderQueryWrapper);
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new BaseException("老人已入住");
        }
        //更新床位状态
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //新增或更新老人信息
        elder = insertOrUpdate(bed, checkInApplyDto.getCheckInElderDto());
        //生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        //新增签约办理
        insertContract(contractNo, elder, checkInApplyDto);
        //新增入住信息
        CheckIn checkIn = insertCheckIn(elder, checkInApplyDto);
        //新增入住配置
        insertCheckInconfig(checkInApplyDto, checkIn);
        //修改智能评测体检报告中的入住状态
        String idCard = checkInApplyDto.getCheckInElderDto().getIdCardNo();
        Integer status = 0;
        healthAssessmentMapper.updateStatusByIdCard(idCard, status);
    }

    private void insertCheckInconfig(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        insertCheckIn(checkIn);
        return checkIn;
    }

    /**
     * 新增签约办理
     *
     * @param contractNo
     * @param elder
     * @param checkInApplyDto
     */
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(Math.toIntExact(elder.getId()));
        contract.setElderName(elder.getName());
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        Integer status = startDate.isBefore(LocalDateTime.now()) ? 0 : 1;
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setStatus(status);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人信息
     *
     * @param bed
     * @param checkInElderDto
     * @return
     */
    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        elderQueryWrapper.eq(Elder::getIdCardNo, elder.getIdCardNo()).ne(Elder::getStatus, 1);
        Elder elderDb = elderMapper.selectOne(elderQueryWrapper);
        if (ObjectUtils.isNotEmpty(elderDb)) {
            elderMapper.updateById(elder);
        } else {
            elderMapper.insert(elder);
        }
        return elder;
    }

    @Override
    @Transactional
    public CheckInDetailVo detail(Long id) {
        CheckIn checkIn = selectCheckInById(id);
        if (checkIn == null) {
            throw new BaseException("入住信息不存在");
        }

        Long elderId = checkIn.getElderId();
        Long checkInId = checkIn.getId();

        Elder elder = elderMapper.selectElderById(elderId);
        if (elder == null) {
            throw new BaseException("老人信息不存在");
        }

        Contract contract = contractMapper.selectContractByElderId(elderId);
        if (contract == null) {
            throw new BaseException("合同信息不存在");
        }

        CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigByCheckId(checkInId);
        if (checkInConfig == null) {
            throw new BaseException("入住配置信息不存在");
        }

        // 解析家属信息
        Object elderFamily = JSON.toJSON(checkInConfig.getRemark());

        //计算年龄
        String idCardNo = elder.getIdCardNo();
        String substring = idCardNo.substring(6, 10);
        int age = Integer.parseInt(LocalDate.now().toString().substring(0, 4)) - Integer.parseInt(substring);

        // 封装数据到 CheckInDetailVo
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Contract contractVo = new Contract();
        BeanUtils.copyProperties(checkIn, checkInConfigVo);
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInElderVo.setAge(age);
        BeanUtils.copyProperties(contract, contractVo);
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contractVo);

        // 单独处理 remark 字段，将其转换为 Json 类型
        String remark = checkIn.getRemark();
        if (remark != null && !remark.isEmpty()) {
            List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);
            checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        } else {
            checkInDetailVo.setElderFamilyVoList(List.of()); // 或者根据需求设为 null
        }

        return checkInDetailVo;
    }
}
